let parents = '', arr = [], element = '', currentIndex = '';
var uploadImg = [] , uploadfile = [] , fileName = [] , gather = [];
function  GetQueryString(name)
{
	var  reg = new  RegExp( "(^|&)" + name + "=([^&]*)(&|$)" );
	var  r = window.location.search.substr(1).match(reg);
	if (r!= null ) return   unescape(r[2]); return  null ;
}

let id = GetQueryString('id');
let ids = GetQueryString('ids');
let type = GetQueryString('type');
let types = GetQueryString('types');

if( types == 1 ){
	$("#signupForms").remove();
}else{
	$("#signupForm").remove();
}

$().ready(function() {
	validateRule();
});

// $.validator.setDefaults({
// 	submitHandler : function() {
// 		save();
// 	}
// });

function save() {
	let video = [] , zySorts = [] , tle = [];
	$("#managementResourcesId").val(id);

	switch (type){
		case "1": $("#level").val(2);$("#parenId").val(ids); break;
		case "2": $("#level").val(3);$("#parenId").val(ids); break;
		default:
			$("#level").val(1)
			$("#parenId").val(id)
	}

	let len = document.getElementsByClassName('link');

	for( let is = 0; is <= len.length - 1; is++ ){

		if( len[is].querySelector('.title').value ){
			tle.push( len[is].querySelector('.title').value )
		}
		// else{
		// 	layer.msg('请输入资源名称')
		// 	return false
		// }
		if( len[is].querySelector('.video').value ){
			video.push( len[is].querySelector('.video').value )
		}
		// else{
		// 	layer.msg('请输入视频链接')
		// 	return false
		// }
		if( len[is].querySelector('.number').value ){
			zySorts.push( len[is].querySelector('.number').value )
		}
		// else{
		// 	layer.msg('请输入优先级')
		// 	return false
		// }

	}


	if( !$("#name").val() ){
		layer.msg('请输入章节名称')
		return false
	}


	// $(".link").each(function (k,v){

		// console.log( $(v).find('.title').val() == '' )
		//
		// if( !$(v).find('.title').val() ){
		// 	layer.msg('请输入资源名称')
		// 	return false
		// }else{
		// 	tle.push( $(v).find('.title').val() )
		// }
		// if( $(v).find('.video').val() ){
		// 	console.log(2)
		// 	video.push( $(v).find('.video').val() )
		// }else{
		// 	console.log(5)
		// 	layer.msg('请输入视频链接')
		// 	return false
		// }
		// if( $(v).find('.number').val() ){
		// 	console.log(3)
		// 	zySorts.push( $(v).find('.number').val() )
		// }else{
		// 	console.log(6)
		// 	layer.msg('请输入优先级')
		// 	return false
		// }

	// })

	$("#zyNames").val(tle.join(','))
	$("#spUrls").val(video.join(','))
	$("#zySorts").val(zySorts.join(','))

	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/zykResourcesChapters/save",
		data : $('#signupForm').serialize(),// 你的formid
		async : false,
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {

				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}

function saves() {

	$("#managementResourcesId").val(id);
	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/zykTypeResources/save",
		data : $('#signupForms').serialize(),// 你的formid
		async : false,
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {

				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}

function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name : {
				required : true
			}
		},
		messages : {
			name : {
				required : icon + "请输入资源名"
			},
			// sort : {
			// 	required : icon + "请输入优先级"
			// },
		}
	})
}


layui.use(['upload', 'layer'], function() {
	var $ = layui.jquery
		, upload = layui.upload
		, layer = layui.layer;
	upload.render({
		elem: '#test2'
		,url: '/common/sysFile/upload' //此处配置你自己的上传接口即可
		,accept: 'file' //普通文件
		,before: function(obj){
			layer.load(1)
			obj.preview(function (index, file, result) {
				fileName.push(file.name);
			})
		}
		,done: function(res){

			if( res.code == 0 ){

				layer.closeAll();
				let str = '' , srr = '' , url = '';
				// gather = [];
				uploadfile.push(res.data);
				// uploadfile.map(function (v,k){
				// 	gather.push({name:fileName[k],file:v})
				// })

				uploadfile.map(function (v,k){
					str += `
						<div class="closeBtn">
							<img class="upImg" src="../../../img/document.png" width="30"/> ${v}
							<span class="iconclose close1" data-index="${k}" ><img src="../../../img/close.png"></span>
						</div>
					  `;
				})
				$(".listAll").html(str)
				$("#wdUrls").val(uploadfile.join(','))

			}

		}
		,error:function (res){
			layer.closeAll();
			layer.msg(res.msg)
		}
	});

	//图片上传
	var uploadInst = upload.render({
		elem: '#test1'
		,url: '/common/sysFile/upload' // 实际使用时改成您自己的上传接口即可。
		,multiple: true
		,before: function(obj){
			layer.load();
		}
		,done: function(res){
			if( res.code == 0 ){
				layer.closeAll();


				if( types == 2 ){
					$("#fileUrl").val(res.data)
					$(".listImg").html(`
					<div class="closeBtn">
							<img class="upImg" src="${res.data}" />
							<span class="iconclose close2"><img src="../../../img/close.png"></span>
						</div>`)
					return false;
				}
				let str = '' ;
				uploadImg.push(res.data);
				$("#tpUrls").val( uploadImg.join(',') )
				uploadImg.map(function (v,k){
					str += `
						<div class="closeBtn">
							<img class="upImg" src="${v}" />
							<span class="iconclose close2" data-index="${k}" ><img src="../../../img/close.png"></span>
						</div>
					  `;
				})
				$(".listImg").html(str)
			}
		}
		,error:function (res){
			layer.closeAll();
			layer.msg(res.msg)
		}
	});

})

$(".addElement").click(function (){
	let str = `<div class="link">
					<input name="" placeholder="请输入资源名称" class="form-control title" type="text">
	
					<input placeholder="请输入视频链接" class="form-control video" type="text">
					<p class="priority"><input type="text" class="form-control number"></p>
					<span class="iconclose remove"><img src="../../../img/close.png"></span>

				</div>`;
	$(".resource").append(str)

})

function removeContent(that, parent, arr, element, index , type) {
	let str = '';

	$(that).parent('.closeBtn').remove();
	arr.splice(index, 1);
	if( type == 1 ){
		let strUrl = [];
		arr.map(function (v,k){
			str += `
				<div class="closeBtn">
					<img class="upImg" src="../../../img/document.png" width="30"/> ${v}
					<span class="iconclose close1" data-index="${k}" ><img src="../../../img/close.png"></span>
				</div>
			  `;
			// strName.push(v.name)
			strUrl.push(v)
		})
		uploadfile = arr
		$("#wdUrls").val(strUrl.join(','))
	}else {
		arr.forEach(function (v, k) {
			str += `
			  <div class="closeBtn">
				<img class="upImg" src="${v}" />
				<span class="iconclose close2" data-index="${k}"><img src="../../../img/close.png"></span>
			  </div>
			`;
		});
		uploadImg = arr
		$("#tpUrls").val( uploadImg.join(',') )
	}
	$(element).html(str);

}

$(document).on('click', '.close2', function() {
	var currentIndex = $(this).data('index');
		arr =  uploadImg;
		parents = '.closeBtn';
		element = '.listImg';
	removeContent(this, parents, arr, element, currentIndex , 2);
});

$(document).on('click', '.close1', function() {
	var currentIndex = $(this).data('index');
	arr =  uploadfile;
	parents = '.closeBtn';
	element = '.listAll';
	removeContent(this, parents, arr, element, currentIndex , 1);
});

$(document).on('click', '.remove', function() {
	let num = $(".link").length - 1;
	if( num <= 0 ){
		layer.msg('已经是最后一个了')
		return false;
	}
	$(this).parents('.link').remove();
});